# Created 2008, Hans Granqvist, hans@granqvist.com
# Released under new BSD License, see
# http://www.opensource.org/licenses/bsd-license.php

require 'sdbm'
require 'webrick' 
include WEBrick 

class Message
  def self.process(query, db)
    type = query['m']
    return set(query, db) if (type == 'set')
    return get(query, db) if (type == 'get')
    return check(query, db) if (type == 'check')
    "bad request"
  end

  def self.set(query, db)
    url = query['url']
    u_hash = query['uh']
    up_hash = query['uph']
    enc = query['e']
    return "missing url" unless url
    return "missing username hash" unless u_hash
    return "missing username/password hash" unless up_hash
    return "missing encrypted username/password" unless enc

    db['up_hash:#{u_hash}:#{url}'] = up_hash
    db['enc:#{u_hash}:#{url}'] = enc
    "ok"
  end

  def self.get(query, db)
    url = query['url']
    u_hash = query['uh']
    return "missing url" unless url
    return "missing username hash" unless u_hash

    db['enc:#{u_hash}:#{url}'] ||= "no such info"
  end

  def self.check(query, db)
    url = query['url']
    u_hash = query['uh']
    return "missing url" unless url
    return "missing username hash" unless u_hash

    db['up_hash:#{u_hash}:#{url}'] ||= "no such info"
  end
end

class PasswordService < HTTPServlet::AbstractServlet 
  def initialize(param)
    super(param)
    @db = SDBM.open "test.db"
  end

  def do_GET(req, res) 
    res['Content-Type'] = "text/plain" 
    res.body = Message.process(req.query, @db) + WEBrick::CRLF
  end 
end 

s = HTTPServer.new( :Port => 2000 ) 
s.mount("/pitc", PasswordService) 
trap("INT"){ s.shutdown } 
s.start

